using System;
using System.Security.Cryptography;
using System.Text;

namespace LiJ.Common.Encrypt
{
	/// <summary>
	/// HMAC哈希加密类
	/// </summary>
	public static class Hmacsha
	{
		/// <summary>
		/// 返回加密后的
		/// </summary>
		/// <param name="data"></param>
		/// <param name="key"></param>
		/// <param name="encoding">如果为空，则默认Utf-8</param>
		/// <param name="encryType">HMAC加密类型：SHA1，SHA256，SHA384，SHA512，MD5</param>
		/// <returns> 解密后的字节流通过Base64转化 </returns>
		public static string EncryptBase64(string data, string key, Encoding encoding = null, string encryType = "SHA1")
		{
			if (encoding == null)
			{
				encoding = Encoding.UTF8;
			}
			byte[] bytes = encoding.GetBytes(data);
			return Convert.ToBase64String(Encrypt(encoding.GetBytes(key), bytes, "SHA1"));
		}

		/// <summary>
		/// 返回加密后的
		/// </summary>
		/// <param name="data"></param>
		/// <param name="key"></param>
		/// <param name="encoding">如果为空，则默认Utf-8</param>
		/// <param name="encryType">HMAC加密类型：SHA1，SHA256，SHA384，SHA512，MD5</param>
		/// <returns></returns>
		public static string Encrypt(string data, string key, Encoding encoding = null, string encryType = "SHA1")
		{
			if (encoding == null)
			{
				encoding = Encoding.UTF8;
			}
			byte[] bytes = encoding.GetBytes(data);
			byte[] bytes2 = Encrypt(encoding.GetBytes(key), bytes);
			return encoding.GetString(bytes2);
		}

		/// <summary>
		/// HMAC加密
		/// </summary>
		/// <param name="key"></param>
		/// <param name="bytes"></param>
		/// <param name="encryType">HMAC加密类型：SHA1，SHA256，SHA384，SHA512，MD5</param>
		/// <returns></returns>
		private static byte[] Encrypt(byte[] key, byte[] bytes, string encryType = "SHA1")
		{
			using (HMAC hMac = GetCryptAlgorithm(key, encryType))
			{
				return hMac.ComputeHash(bytes);
			}
		}

		private static HMAC GetCryptAlgorithm(byte[] key, string encryType = "SHA1")
		{
			if (encryType != "SHA256")
			{
				if (encryType != "SHA384")
				{
					if (encryType != "SHA512")
					{
						if (encryType == "MD5")
						{
							return new HMACMD5(key);
						}
						return new HMACSHA1(key);
					}
					return new HMACSHA512(key);
				}
				return new HMACSHA384(key);
			}
			return new HMACSHA256(key);
		}
	}
}
